<template>
  <Drawer ref="refDrawer" title="签章信息" @change="onVisibleChange">
    <div id="signatureItem">
      <el-tabs v-model="style.activeTabName" class="demo-tabs">
        <el-tab-pane label="摘要" name="tabAbstract">
          <div class="box-infos scrollbar-auto overflow-x-hidden">
            <div class="item" v-for="item in state.fields.abstract">
              <div class="label">{{ item.label }}</div>
              <div class="desc">
                <template v-if="item.fieldKey == 'signatureStatus'">
                  <StatusBoolean
                    trueText="签名有效，证书链完整"
                    falseText="签名无效"
                    v-model="formData.verifyAbstract[item.fieldKey]"
                  ></StatusBoolean>
                </template>
                <template v-else>
                  {{ formateDesc(formData.verifyAbstract[item.fieldKey]) }}
                </template>
              </div>
            </div>
            <div
              class="opacity-0 p-4 bg-red-100/60 rounded-md my-4 animate__bounceInRight text-[12px]"
              style="animation-delay: 0.35s"
              v-if="formData.verifyAbstract.signatureStatus === false"
            >
              <div class="mb-2 font-bold text-[#666]">无效原因：</div>
              <div
                class="item-info"
                v-for="(item, index) in formData.verifyAbstract
                  .verifyResultRemark"
              >
                {{ index + 1 }}. {{ item }}
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="证书信息" name="tabCert" v-if="formData.verifyCert">
          <div class="box-infos scrollbar-auto">
            <div class="item" v-for="item in state.fields.cert">
              <div class="label">{{ item.label }}</div>
              <div class="desc">
                {{ formateDesc(formData.verifyCert[item.fieldKey]) }}
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="印章信息" name="tabSeal" v-if="formData.verifySeal">
          <div class="box-infos scrollbar-auto">
            <div class="item" v-for="item in state.fields.seal">
              <div class="label">{{ item.label }}</div>
              <div class="desc">
                <template v-if="item.fieldKey == 'certListType'">
                  {{ mapping.certListType(formData.verifySeal[item.fieldKey]) }}
                </template>
                <template v-else>
                  {{ formateDesc(formData.verifySeal[item.fieldKey]) }}
                </template>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </Drawer>
</template>
<script setup>
import { reactive, toRefs, ref, inject, watchEffect, watch } from "vue";
import { http, ss, seal } from "@/utils";
import $ from "jquery";

const refDrawer = ref();
const provideHome = inject("provideHome");

const state = reactive({
  style: {
    activeTabName: "tabAbstract",
    // 签章详情是否处于显示状态
    visibleDetail: false,
  },
  formData: {
    verifyAbstract: {},
    verifyCert: {},
    verifySeal: {},
  },
  fields: {
    //摘要
    abstract: [
      {
        label: "签名者",
        fieldKey: "signer",
      },
      {
        label: "签名状态",
        fieldKey: "signatureStatus",
      },
      {
        label: "证书颁发者",
        fieldKey: "issuer",
      },
      {
        label: "证书生效时间",
        fieldKey: "validityNotBefore",
      },
      {
        label: "证书过期时间",
        fieldKey: "validityNotAfter",
      },
      {
        label: "签名时间",
        fieldKey: "signatureTime",
      },
      {
        label: "签名地点",
        fieldKey: "signLocation",
      },
      {
        label: "签名原因",
        fieldKey: "signReason",
      },
    ],
    //证书
    cert: [
      {
        label: "版本",
        fieldKey: "version",
      },
      // {
      //   label: "序列号",
      //   fieldKey: "certSn",
      // },
      {
        label: "签名算法",
        fieldKey: "sigAlg",
      },
      {
        label: "颁发者",
        fieldKey: "issuer",
      },
      {
        label: "有效期从",
        fieldKey: "validityNotBefore",
      },
      {
        label: "有效期到",
        fieldKey: "validityNotAfter",
      },
      {
        label: "公钥",
        fieldKey: "publicKey",
      },
      {
        label: "证书序列号",
        fieldKey: "certSn",
      },
      // {
      //   label: "公钥参数",
      //   fieldKey: "kings",
      // },
      {
        label: "授权密钥标识符",
        fieldKey: "authKeyIdentifier",
      },
      {
        label: "签章者密钥标识符",
        fieldKey: "signerKeyIdentifier",
      },
      {
        label: "基本约束",
        fieldKey: "fundamentalConstraint",
      },
      {
        label: "密钥用法",
        fieldKey: "keyUsage",
      },
    ],
    //印章
    seal: [
      {
        label: "版本",
        fieldKey: "version",
      },
      {
        label: "厂商标识",
        fieldKey: "vId",
      },
      {
        label: "印章编码",
        fieldKey: "esId",
      },
      {
        label: "印章类型",
        fieldKey: "type",
      },
      {
        label: "印章名称",
        fieldKey: "name",
      },
      {
        label: "签章者证书信息类型",
        fieldKey: "certListType",
      },
      {
        label: "签章者证书信息列表",
        fieldKey: "_certList",
      },
      {
        label: "制作时间",
        fieldKey: "createDate",
      },
      {
        label: "生效时间",
        fieldKey: "validStart",
      },
      {
        label: "过期时间",
        fieldKey: "validEnd",
      },
      {
        label: "图像类型",
        fieldKey: "imgType",
      },
      {
        label: "图像显示宽度",
        fieldKey: "imgWidth",
      },
      {
        label: "图像显示高度",
        fieldKey: "imgHeight",
      },
    ],
  },
});
const { style, formData } = toRefs(state);

const onVisibleChange = newStatus => {
  state.style.visibleDetail = newStatus;
};

const onReset = () => {
  state.formData = {
    verifyAbstract: {},
    verifyCert: {},
    verifySeal: {},
  };
  if (!state.style.visibleDetail) {
    state.style.activeTabName = "tabAbstract";
  }
};

const formateDesc = inValue => {
  return inValue || "--";
};

const getInfos = async () => {
  onReset();
  let { signatureDomainId } = provideHome.selectedSignature;
  const [err, res] = await http.post({
    showLoading: "#rightContainer",
    data: {
      serviceCode: "verifyElectronicSealSignature",
      featureCode: "getFileElectronicSealSignatureInfo",
      businessData: {
        fileId: ss.get("fileId"),
        signatureDomainId,
      },
    },
  });
  if (res) {
    state.formData = res;

    let { verifySeal } = state.formData;
    //设置签章的验证结果
    provideHome.signatureValidateResult[
      seal.formatSignatureDomainId(signatureDomainId)
    ] = res.verifyAbstract.signatureStatus;
    setSignatureStatusInViewer();
    if (verifySeal) {
      let { certListType } = verifySeal;

      if (certListType == 1) {
        //数字证书
        state.formData.verifySeal._certList = verifySeal.certSnList.join("、");
      } else if (certListType == 2) {
        //数字证书杂凑值
        state.formData.verifySeal._certList =
          verifySeal.certHashList.join("、");
      }
    }
  } else {
    refDrawer.value.close();
  }
};

const mapping = {
  certListType(inValue) {
    let map = {
      1: "数字证书",
      2: "数字证书杂凑值",
    };
    return map[inValue] || "-";
  },
};

const setSignatureStatusInViewer = () => {
  let { signatureDomainId } = provideHome.selectedSignature;
  let { signatureValidateResult } = provideHome;
  let isValid =
    signatureValidateResult[seal.formatSignatureDomainId(signatureDomainId)];
  let validResult = "unknown";
  if (typeof isValid == "boolean") {
    if (isValid) {
      validResult = "pass";
    } else {
      validResult = "notpass";
    }
  }
  let $el = $(`[data-field-name="${signatureDomainId}"]`);
  if ($el.length) {
    $el[0].dataset.validResult = validResult;
  }
};

watch(
  () => provideHome.selectedSignature.signatureDomainId,
  () => {
    let { signatureDomainId } = provideHome.selectedSignature;
    if (signatureDomainId) {
      $(".signature-active").removeClass("signature-active");
      $(`[data-field-name="${signatureDomainId}"]`).addClass(
        "signature-active"
      );
      setSignatureStatusInViewer();
      if (state.style.visibleDetail) {
        //签章详情显示时，更新签章详情
        getInfos();
      }
    } else {
      // 在打开签章详情时，重新导入文档，会走这个逻辑分支
      refDrawer.value.close();
    }
  }
);

const showDetailDrawer = () => {
  refDrawer.value.show();
  getInfos();
};

//浏览区印章点击事件
$("#viewer").on("click", ".signature-annotation", function () {
  provideHome.selectedSignature.signatureDomainId = $(this).data("fieldName");
  showDetailDrawer();
});
</script>
<style lang="scss">
#signatureItem {
  @apply h-full;
  .box-infos {
    background: #f8f8f8;
    border-radius: 4px;
    max-height: 100%;
    box-sizing: border-box;

    padding: 8px 8px;
    @apply pr-3;
    .item {
      @apply flex leading-[18px] mb-[6px] text-[12px];
      .label {
        @apply w-[90px] text-[#969AA0] shrink-0;
        &:after {
          content: "：";
        }
      }
      .desc {
        @apply text-[#333] break-all;
      }
    }
  }
  .el-tabs {
    @apply h-full flex flex-col;
    .el-tabs__content {
      @apply flex-1;
      .el-tab-pane {
        @apply h-full;
      }
    }
  }
  #pane-tabCert {
    .label {
      width: 110px;
    }
  }
  #pane-tabSeal {
    .label {
      width: 110px;
    }
  }
}
</style>
